package com.bdrm.controller.admin;


import com.bdrm.dto.DishDTO;
import com.bdrm.dto.DishPageQueryDTO;
import com.bdrm.result.PageResult;
import com.bdrm.result.Result;
import com.bdrm.service.DishService;

import com.bdrm.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@Api(tags = "菜品接口")
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("菜品分页查询")
    @PostMapping("/page")
    public Result<PageResult> page(@RequestBody DishPageQueryDTO dishPageQueryDTO){
        log.info("菜品分页查询：{}",dishPageQueryDTO.getStatus());
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @ApiOperation("添加菜品")
    @PostMapping("/save")
    public Result save(@RequestBody DishDTO dishDTO){
        System.out.println("添加"+dishDTO);
        dishService.saveWithFlavor(dishDTO);

        // 清理缓存
        String key = "dish_" + dishDTO.getCategoryId();
        cleanCache(key);
        return Result.success();
    }

    @ApiOperation("根据id查询数据")
    @PostMapping("/{id}")
    public Result<DishVO> getDishById(@PathVariable Long id){
        DishVO dish = dishService.getDishById(id);
        return Result.success(dish);
    }

    @ApiOperation("根据id修改数据")
    @PutMapping("/update")
    public Result update(@RequestBody DishDTO dishDTO){
        dishService.updateWithFlavor(dishDTO);

        cleanCache("dish_*");
        return Result.success();
    }

    @ApiOperation("删除菜品")
    @DeleteMapping
    public Result deleteById(@RequestParam List<Long> ids){
        dishService.deleteById(ids);

        cleanCache("dish_*");
        return Result.success();
    }

    @ApiOperation("起售停售")
    @PutMapping("/{status}/{id}")
    public Result updateStatus(@PathVariable Integer status,@PathVariable Long id){
        dishService.updateStatus(status,id);

        cleanCache("dish_*");
        return Result.success();
    }

    // 清理缓存数据
    private void cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
